package cn.net.wanji.task;

import cn.net.wanji.config.ApplicationConfig;
import cn.net.wanji.utils.DiskUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileFilter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class FolderDeletion {
    @Resource
    private ApplicationConfig applicationConfig;
    private final static Logger deleteFileLogger = LoggerFactory.getLogger("file");


    void deleteFoldersByDescendingDate(String directoryPath) {
        File directory = new File(directoryPath);
        //只获取文件夹
        File[] subdirectories = directory.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                if (file.isDirectory()) {
                    boolean validDateFormat = isValidDateFormat(file.getName());
                    return validDateFormat;
                }else {
                    return false;
                }
            }
        });
        if (subdirectories == null) {
            return ;
        }
        Arrays.sort(subdirectories, new FolderComparator());
        List<String> absolutePaths = new ArrayList<>();
        for (int i = 0; i < subdirectories.length; i++) {
            String absolutePath = subdirectories[i].getAbsolutePath();
            absolutePaths.add(absolutePath);
            if (subdirectories[i].isFile()) {
                continue;
            }
            String folderName = subdirectories[i].getName();
            if (!isValidDateFormat(folderName)) {
                continue;
            }
            Double discPercentage = applicationConfig.getDiscPercentage();
            String rootDirectory = getRootDirectory(applicationConfig.getFileSavePath("1"));
//            double fileLogPercentage = viewDiskCapacity(rootDirectory);
            double fileLogPercentage= DiskUtils.getMountPointAndDiskUsage(applicationConfig.getFileSavePath("1"));
            if (subdirectories.length-i > 30&&fileLogPercentage>discPercentage) {
                deleteDirectory(subdirectories[i].getPath());
//                 deleteFolder(subdirectories[i]);
                deleteFileLogger.info(" clear viewDiskCapacity log file data: " + subdirectories[i].getAbsolutePath() + "日志磁盘占比：" + fileLogPercentage);
            }

        }

        deleteFileLogger.info("end clear cleanupEvery30Seconds log file before 30 data" );
//        for (File subdirectory : subdirectories) {
//            if (subdirectory.isFile()) {
//                continue;
//            }
//            String folderName = subdirectory.getName();
//            if (!isValidDateFormat(folderName)) {
//                continue;
//            }
//
//            deleteFolder(subdirectory);
//        }

    }

    private  boolean isValidDateFormat(String folderName) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        try {
            dateFormat.parse(folderName);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    private void   deleteFolder(File folder) {
        File[] files = folder.listFiles();
        if (files == null) {
            return ;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                deleteFolder(file);
            } else {
                file.delete();
            }
        }



    }

    private  class FolderComparator implements Comparator<File> {
        private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        @Override
        public int compare(File o1, File o2) {
            String date1 = o1.getName();
            String date2 = o2.getName();
            try {
                Date d1 = dateFormat.parse(date1);
                Date d2 = dateFormat.parse(date2);
                return d1.compareTo(d2);
            } catch (ParseException e) {
                e.printStackTrace();
                return 0;
            }
        }
    }
    private String getRootDirectory(String path) {
        Path fullPath = Paths.get(path);
        Path root = fullPath.getRoot();

        return root.toString();
    }

    /*
     * 根据磁盘路径查看磁盘可用比例
     * */
//    private double viewDiskCapacity(String path) {
//        File file = new File(path);
//        long totalSpace = file.getTotalSpace(); // 获取磁盘的总空间
////        long freeSpace = file.getFreeSpace(); // 获取磁盘的可用空间
//        long usableSpace = file.getUsableSpace();//获取可用磁盘
//
//        double availablePercentage = (double) (totalSpace - usableSpace) / totalSpace * 100;
//        return availablePercentage;
//    }

    public static void deleteDirectory(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (file.isFile()) {
            file.delete();
            // 清理文件
        } else {

            File[] list = file.listFiles();
            if (list != null) {
                for (File f : list) {
                    deleteDirectory(f.getAbsolutePath());
                }
                file.delete();//清理目录
            }
        }
    }
}

